import ApiOptions from "../api/index.js";
import { ref } from "vue";
import { systemInfo } from "../tools/system.js";
import { onMounted } from "vue";
import { showToast } from "vant";
import { useStore } from "vuex";
import { onShow } from "@dcloudio/uni-app";
import { getRouteParams, logout } from "../tools/tools.js";

/** 登录过期 401 处理 */
export const useApi = (apiSign) => {
  const store = useStore();
  const signList = typeof apiSign === "string" ? [apiSign] : apiSign;

  return [
    /*onSubmit*/
    ...signList.map((sign) => async (params) => {
      const res = await ApiOptions[sign](params);
      // 登出处理
      if (res.code === 401)
        return logout(res, async () => {
          await store.dispatch("user/resetUserInfo");
        });

      return res;
    }),
    store,
  ];
};

/** 跳转--带限制提示 */
export const useJumpPage = (msg = "请先登录") => {
  const store = useStore();

  const to = ([type], url) => {
    const mapper = {
      navigate: "navigateTo",
      redirect: "redirectTo",
      switchTab: "switchTab",
      reLaunch: "reLaunch",
    };
    if (store.getters["user/isLogin"])
      uni[type ? mapper[type] : "navigateTo"]({ url });
    else showToast(msg);
  };

  return [to, store];
};

/** 获取中英文状态 */
export const useLang = (store) => {
  return store.getters["config/isZh"] ? "zh" : "en";
};

/** 隐藏默认tabbar */
export const useHideTabbar = () => {
  onShow(() => uni.hideTabBar());
};

export const usePageBoundary = () => {
  const contentHeight = ref(0);
  const heightWithBar = ref(0);
  onMounted(() => {
    const { windowHeight, windowTop, windowBottom } = systemInfo();
    contentHeight.value = windowHeight - windowTop + 'px';
    heightWithBar.value = windowHeight - windowTop - windowBottom + 'px';
  });
  return { contentHeight, heightWithBar };
};
